package cn.sinjet.model.carassist;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import cn.sinjet.entity.ShortPOI;

/*
 * SinjetService
 * @author:  Kevin.Ye
 * In this Service,We will do as below:
 * when app exites from exception,we will send the record
 * 
 */

public class SinjetService extends Service{
	  static final String tag = "remote_service";
      //private final IBinder  serviceBinder = new ServiceBinder();
      
      private final Messenger mMessager = new Messenger(new ServiceHandler());
      private  Messenger mAppClient = null;
      final static int START_POINT = 1;
      final static int END_POINT = 2;
      final static int APP_INIT = 3;
      final static int PAGE_ID = 4;
      final static int CUR_POS = 5;
      ShortPOI mStartPoint = null;
      ShortPOI mEndPoint = null;
      private int mPageId = 0;
	  private int mStartId;
	  boolean mIsAppReboot = false;

	public double mLatitude;

	public double mLongitude;
      class ServiceHandler extends Handler{
    	  

		@Override 
    	public void handleMessage(Message msg) {
    		// TODO Auto-generated method stub
    		super.handleMessage(msg);
    		Log.d(tag, "handlerMessage what="+msg.what);
    		switch(msg.what){
    		case 100:
    			mAppClient = msg.replyTo;
    			break;
    		case START_POINT:{
    			ShortPOI poi = new ShortPOI();
				Bundle bundle = msg.getData();
				poi.id =  bundle.getString("id");
		        poi.title =  bundle.getString("title");
		        poi.address = bundle.getString("address");
		        poi.latitude =  bundle.getDouble("latitude");
		        poi.longitude =  bundle.getDouble("longitude");
		        poi.isCurrentPosition =  bundle.getBoolean("current");
    			mStartPoint = poi;
    		}break;
    		case END_POINT:{
    			ShortPOI poi = new ShortPOI();
				Bundle bundle = msg.getData();
				poi.id =  bundle.getString("id");
		        poi.title =  bundle.getString("title");
		        poi.address = bundle.getString("address");
		        poi.latitude =  bundle.getDouble("latitude");
		        poi.longitude =  bundle.getDouble("longitude");
		        poi.isCurrentPosition =  bundle.getBoolean("current");
    			mEndPoint = poi;
    		}break;
    		case APP_INIT:
    			if(mIsAppReboot){
    				mIsAppReboot = false;
	    			sendCurPostion(mLatitude, mLongitude);
	    			sendStartPoint(mStartPoint);
	    			sendEndPoint(mEndPoint);
	    			sendPageId(mPageId);
    			}
    			break;
    		case PAGE_ID:
    			mPageId = msg.arg1;
    			break;
    		case CUR_POS:
    			Bundle bundle = msg.getData();
    			mLatitude =  bundle.getDouble("latitude");
    	        mLongitude = bundle.getDouble("longitude");
    			break;
    		}
    	}
      }
     
      
	@Override
	public IBinder onBind(Intent intent) {
//		 TODO Auto-generated method stub
        Log.d(tag, "onBind flag:"+intent.getFlags());  //Init service after binded
		//return serviceBinder;
        return mMessager.getBinder();
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d(tag,"onUnbind");
		return super.onUnbind(intent);
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d(tag, "onCreate");
	
		new BackGroundThread().start();
	}
	
//	@SuppressWarnings("deprecation")
	@SuppressWarnings("deprecation")
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(tag,"onStartCommand flag:"+flags+" startId:"+startId);
		/* Notification notification = new Notification(R.drawable.ic_launcher,getString(R.string.app_name), System.currentTimeMillis());
		 PendingIntent pendingintent = PendingIntent.getActivity(this, 0,new Intent(this, SinjetService.class), 0);
		 notification.setLatestEventInfo(this, "信界导航", "在后台持续为您服务",pendingintent);
		 startForeground(0x111, notification);*/
		 if(mStartId != startId)
			 mIsAppReboot = true;
		 mStartId = startId;
		return super.onStartCommand(intent, flags, startId);
	}
	
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(tag,"onDestory");
		super.onDestroy();
	}
	
	
	/*public class ServiceBinder extends Binder {
		public SinjetHUDService getService() {
			return SinjetHUDService.this;
		}
	}*/

	
	class BackGroundThread extends Thread{
		  @Override
		public void run() {
			// TODO Auto-generated method stub
//			super.run();
			  while(true){
				  try{
					  Thread.sleep(3000);
					  Log.d(tag,"Background thread is alived");
					  /*Message msg = Message.obtain(null, 11);
					  if(null != mAppClient)
					  mAppClient.send(msg);*/
				  }catch(Exception e){
					  e.printStackTrace();
				  }
			  }
		}
	}
	
	private void sendStartPoint(ShortPOI poi){
		if(poi == null) return;
	   try{
		   Message msg = Message.obtain(null,START_POINT);
	    	  Bundle bundle = new Bundle();
	    	  bundle.putString("id", poi.id);
	          bundle.putString("title", poi.title);
	          bundle.putString("address", poi.address);
	          bundle.putDouble("latitude", poi.latitude);
	          bundle.putDouble("longitude", poi.longitude);
	          bundle.putBoolean("current", poi.isCurrentPosition);
	          msg.setData(bundle);
		   if(null != mAppClient)  
			   mAppClient.send(msg);
	   }catch(RemoteException e){
		   e.printStackTrace();
	   }			
	}
	private void sendEndPoint(ShortPOI poi){
		if(poi == null) return;
	     Message msg = Message.obtain(null,END_POINT);
	     Bundle bundle = new Bundle();
    	  bundle.putString("id", poi.id);
          bundle.putString("title", poi.title);
          bundle.putString("address", poi.address);
          bundle.putDouble("latitude", poi.latitude);
          bundle.putDouble("longitude", poi.longitude);
          bundle.putBoolean("current", poi.isCurrentPosition);
          msg.setData(bundle);
         sendMsgToAppClient(msg); 
	}
	
   private void sendPageId(int pageId){
	   Message msg = Message.obtain(null,PAGE_ID);
	   msg.arg1 = pageId;
	   sendMsgToAppClient(msg);
   }
   
   private void sendMsgToAppClient(Message msg){
	   try{
		   if(null != mAppClient)  
			   mAppClient.send(msg);
	   }catch(RemoteException e){
		   e.printStackTrace();
	   }
   }
   
   public void sendCurPostion(double latitude,double longitude){
 	  Message msg = Message.obtain(null, CUR_POS);
 	  Bundle bundle = new Bundle();
       bundle.putDouble("latitude", latitude);
       bundle.putDouble("longitude", longitude);
       msg.setData(bundle);
       sendMsgToAppClient(msg);
   }
}
